package cn.time1024.time_app.ui.video

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import cn.time1024.time_app.databinding.FragmentVideoListBinding
import cn.time1024.time_app.ui.player.VideoPlayerActivity

class VideoListFragment : Fragment() {

    private var _binding: FragmentVideoListBinding? = null
    private val binding get() = _binding!!

    private val videos = listOf(
        Pair("示例视频1", "https://samplelib.com/lib/preview/mp4/sample-5s.mp4"),
        Pair("示例视频2", "https://samplelib.com/lib/preview/mp4/sample-10s.mp4")
    )

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        _binding = FragmentVideoListBinding.inflate(inflater, container, false)
        setupList()
        return binding.root
    }

    override fun onDestroyView() { super.onDestroyView(); _binding = null }

    private fun setupList() {
        binding.rvVideos.layoutManager = LinearLayoutManager(requireContext())
        binding.rvVideos.adapter = object : androidx.recyclerview.widget.RecyclerView.Adapter<VideoVH>() {
            override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VideoVH {
                val v = layoutInflater.inflate(cn.time1024.time_app.R.layout.item_video, parent, false)
                return VideoVH(v)
            }
            override fun getItemCount(): Int = videos.size
            override fun onBindViewHolder(holder: VideoVH, position: Int) {
                val (title, url) = videos[position]
                holder.tvTitle.text = title
                holder.btnPlay.setOnClickListener {
                    val i = Intent(requireContext(), VideoPlayerActivity::class.java)
                    i.putExtra("video_url", url)
                    startActivity(i)
                }
            }
        }
    }
}

class VideoVH(itemView: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(itemView) {
    val tvTitle: android.widget.TextView = itemView.findViewById(cn.time1024.time_app.R.id.tvTitle)
    val btnPlay: View = itemView.findViewById(cn.time1024.time_app.R.id.btnPlay)
}

